package com.ujiuye.filter;

import com.ujiuye.enity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc) throws IOException, ServletException {
        //向下的类型强转
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;
        //获取请求路径
        String uri = req.getRequestURI();
        //截取获取最终的简化的请求路径
        String uriPath = uri.substring(uri.lastIndexOf("/") + 1);
        //判断那些请求不需要登录校验,比如:登录页面，登录请求,注册页面，注册请求
        if("register.html".equals(uriPath)||"register".equals(uriPath)
                ||"login.jsp".equals(uriPath)||"login".equals(uriPath)){
            //直接放行
            fc.doFilter(req,resp);
        }else{
            //需要进行登录安全校验
            HttpSession session = req.getSession();
            User user = (User)session.getAttribute("u");
            if(user!=null){
                //登录成功
                fc.doFilter(req,resp);
            }else{
                //去登录
                resp.sendRedirect("login.jsp");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
